package org.suburban.servlet.staticdata;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.WARNING;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.suburban.servlet.XMPPServlet;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import static org.suburban.resource.RequestParams.*;

/**
 * Class to query information about stations, belonged to particular direction 
 * @author Alexey Palamarchuk (slonnik@gmail.com)
 *
 */
@SuppressWarnings({"serial","rawtypes"})
public final class StationsServlet  extends XMPPServlet{
	/** logger*/
	private static final Logger logger = Logger.getLogger(StationsServlet.class.getName());
	/** HTTP query template */
	private static final String template = "http://m.rasp.yandex.ru/direction?direction=%1$s";
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	
		/** let's trace request info*/
		if(logger.isLoggable(FINE))
		{
			Map params = req.getParameterMap();
			logger.log(FINE, "\'stations\' request arrived with the following params {0}", params);
		}
		/** get direction*/
		String direction = req.getParameter(DIRECTION);
		if(direction == null)
		{
			logger.warning("Description parameter is not set");
			return;
		}
		/** trace query*/
		String url = String.format(template, direction);
		if(logger.isLoggable(FINE))
		{
			logger.log(FINE, "\'stations\' request looks like: {0}", url);
		}
		
		String data = fetchURL(url, "UTF-8");
		int start = data.indexOf("<div");
		start = data.indexOf("<select", start);
		int end = data.indexOf("</select", start);
		data = data.substring(start, end) + "</select>";
		
		logger.log(FINE, "Stations data: {0}", data);
		/** parse data */
		try
		{
			SAXParserFactory factory = SAXParserFactory.newInstance();
	        factory.newSAXParser().parse(new InputSource(new StringReader(data)),
	        		new StationsCracker(direction));
		}
		catch(ParserConfigurationException ex)
		{
			logger.log(WARNING,"Failed to parse HTML response: {}", ex.getMessage());
			return;
		}
		catch(SAXException ex)
		{
			logger.log(WARNING,"Failed to parse HTML response: {}", ex.getMessage());
			return;
		}
	}
}
